#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::PermissionBean;
use crate::domain::PermissionQueryRequest;
use crate::serviceimpl::permission_service::activate_all_permissions as service_activate_all_permissions;
use crate::serviceimpl::permission_service::activate_permission as service_activate_permission;
use crate::serviceimpl::permission_service::add_permission as service_add_permission;
use crate::serviceimpl::permission_service::clone_all_permissions as service_clone_all_permissions;
use crate::serviceimpl::permission_service::clone_permission as service_clone_permission;
use crate::serviceimpl::permission_service::count_search_permissions_by_fields_records as service_count_search_permissions_by_fields_records;
use crate::serviceimpl::permission_service::delete_all_permissions as service_delete_all_permissions;
use crate::serviceimpl::permission_service::delete_permission as service_delete_permission;
use crate::serviceimpl::permission_service::find_permission_by_id as service_find_permission_by_id;
use crate::serviceimpl::permission_service::find_permission_by_perm_name as service_find_permission_by_perm_name;
use crate::serviceimpl::permission_service::list_active_permissions as service_list_active_permissions;
use crate::serviceimpl::permission_service::list_all_permissions as service_list_all_permissions;
use crate::serviceimpl::permission_service::search_permissions_by_fields as service_search_permissions_by_fields;
use crate::serviceimpl::permission_service::search_permissions_by_fields_by_page as service_search_permissions_by_fields_by_page;
use crate::serviceimpl::permission_service::soft_delete_all_permissions as service_soft_delete_all_permissions;
use crate::serviceimpl::permission_service::soft_delete_permission as service_soft_delete_permission;
use crate::serviceimpl::permission_service::toggle_one_permission as service_toggle_one_permission;
use crate::serviceimpl::permission_service::toggle_permission as service_toggle_permission;
use crate::serviceimpl::permission_service::update_permission as service_update_permission;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionRequest {
	pub id: Option<i64>,
	pub perm_name: Option<String>,
	pub active: Option<bool>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

pub fn permission_controller() -> Router {
	Router::new()
	.route("/listAllPermissions", post(list_all_permissions))
	.route("/updatePermission", post(update_permission))
	.route("/deletePermission", post(delete_permission))
	.route("/addPermission", post(add_permission))
	.route("/softDeletePermission", post(soft_delete_permission))
	.route("/findPermissionById", post(find_permission_by_id))
	.route("/findPermissionByPermName", post(find_permission_by_perm_name))
	.route("/listActivePermissions", post(list_active_permissions))
	.route("/deleteAllPermissions", post(delete_all_permissions))
	.route("/softDeleteAllPermissions", post(soft_delete_all_permissions))
	.route("/togglePermission", post(toggle_permission))
	.route("/toggleOnePermission", post(toggle_one_permission))
	.route("/searchPermissionsByFieldsByPage", post(search_permissions_by_fields_by_page))
	.route("/activatePermission", post(activate_permission))
	.route("/activateAllPermissions", post(activate_all_permissions))
	.route("/exportPermissions", get(export_permissions))
	.route("/exportPermissionsPDF", get(export_permissions_pdf))
	.route("/filterPermissionsExcel", get(filter_permissions_excel))
	.route("/filterPermissionsPDF", get(filter_permissions_pdf))
	.route("/clonePermission", post(clone_permission))
	.route("/cloneAllPermissions", post(clone_all_permissions))
	.route("/checkAccessPermission", get(check_access_permission))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_permissions(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_permissions(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_activate_permission(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_permission(Json(permission_request):Json<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let perm_name = permission_request.perm_name.unwrap_or_default();
	let active = permission_request.active.unwrap_or_default();

	let permission = PermissionBean{
	id : id,
	perm_name : perm_name,
	active : active,
	};
	
	let _result = service_add_permission(permission).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn check_access_permission() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_permissions(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_permissions(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_clone_permission(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_permissions(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_permissions(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_delete_permission(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_permissions() ->Response<Body> {
	let list = service_list_all_permissions().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "许可信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for permission in list {

		let row = vec![permission.id.to_string(),permission.perm_name,permission.active.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/permissions.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=permissions.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_permissions_pdf() ->Response<Body> {
	let list = service_list_all_permissions().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "许可信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for permission in list {

		let row = vec![permission.id.to_string(),permission.perm_name,permission.active.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);
	
	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=permissions.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_permissions_excel(Query(permission_query_request):Query<PermissionQueryRequest>) ->Response<Body> {
	let list = service_search_permissions_by_fields(permission_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "许可信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for permission in list {

		let row = vec![permission.id.to_string(),permission.perm_name,permission.active.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/permissions.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=permissions.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_permissions_pdf(Query(permission_query_request):Query<PermissionQueryRequest>) ->Response<Body> {
	let list = service_search_permissions_by_fields(permission_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "许可信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string()];
	let is_images = vec![false,false,false];
	for permission in list {

		let row = vec![permission.id.to_string(),permission.perm_name,permission.active.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=permissions.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_permission_by_id(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let permission = service_find_permission_by_id(id).await;
	match permission {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(permission) => {
			let json = serde_json::to_string_pretty(&permission).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_permission_by_perm_name(Form(permission_request):Form<PermissionRequest>) ->String {
	let perm_name = permission_request.perm_name.unwrap_or_default();
	let permission = service_find_permission_by_perm_name(perm_name).await;
	match permission {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(permission) => {
			let json = serde_json::to_string_pretty(&permission).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_permissions() ->String {
	let permissions = service_list_active_permissions().await;
	match permissions {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(permissions) => {
			let json = serde_json::to_string_pretty(&permissions).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_permissions() ->String {
	let permissions = service_list_all_permissions().await;
	match permissions {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(permissions) => {
			let json = serde_json::to_string_pretty(&permissions).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_permissions_by_fields_by_page(Form(permission_query_request):Form<PermissionQueryRequest>) ->String {
	let permissions = service_search_permissions_by_fields_by_page(permission_query_request.clone()).await;
	let total = service_count_search_permissions_by_fields_records(permission_query_request.clone()).await.unwrap().count_num;
	match permissions {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(permissions) => {
			let json = serde_json::to_string_pretty(&permissions).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_permissions(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_permissions(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_soft_delete_permission(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_toggle_one_permission(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_permission(Form(permission_request):Form<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let _result = service_toggle_permission(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_permission(Json(permission_request):Json<PermissionRequest>) ->String {
	let id = permission_request.id.unwrap_or_default();
	let perm_name = permission_request.perm_name.unwrap_or_default();
	let active = permission_request.active.unwrap_or_default();
	let _current_permission = service_find_permission_by_id(id).await.unwrap();

	let permission = PermissionBean{
	id : id,
	perm_name : perm_name,
	active : active,
	};
	
	let _result = service_update_permission(permission).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

